package org.example;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo2_DataSource {
    public static void main(String[] args) {
        //创建MySQL 数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/javatest?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        //用户名
        mysqlDataSource.setUser("root");
        //密码
        mysqlDataSource.setPassword("123456");

        //定义JDBC 的数据源对象
        DataSource dataSource = mysqlDataSource;

        //定义连接对象
        Connection connection = null;
        //定义预处理SQL对象
        PreparedStatement statement = null;
        //定义结果集
        ResultSet resultSet = null;

        try{
            //1. 通过数据源进行数据库的连接
            connection = dataSource.getConnection();
            // 2. 获取预处理SQL执行对象
            //定义要执行的SQL
            String sql = "select student_id, sn, name, mail, class_id from student where name = ?";
            statement = connection.prepareStatement(sql);
            //接收用户的输入
            System.out.println("请输入学生姓名：");
            Scanner in = new Scanner(System.in);
            String name = in.nextLine();
            //3. 用真实的数据替换占位符
            statement.setString(1,name);
            // 4. 执行SQL，获取结果集
            resultSet = statement.executeQuery();
            //遍历结果集
            while(resultSet.next()) {
                //获得结果集的每一列数据
                long stuId = resultSet.getLong("student_id");
                String stuSn = resultSet.getString("sn");
                String stuNam = resultSet.getString("name");
                String stuMail = resultSet.getString("mail");
                long claId = resultSet.getLong("class_id");
                //输出结果集
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 姓名={2}, 邮箱={3}, 班级编号={4}",stuId,
                        stuSn,stuNam,stuMail,claId));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
